package org.millioncall.yueyoga.admin.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.NumberUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.Order;
import org.millioncall.yueyoga.admin.model.OrderDetail;
import org.millioncall.yueyoga.admin.model.Product;
import org.millioncall.yueyoga.admin.model.ProductRemaining;
import org.millioncall.yueyoga.admin.model.Remaining;
import org.millioncall.yueyoga.admin.model.Site;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.OrderDetailService;
import org.millioncall.yueyoga.admin.service.OrderService;
import org.millioncall.yueyoga.admin.service.ProductRemainingService;
import org.millioncall.yueyoga.admin.service.ProductService;
import org.millioncall.yueyoga.admin.service.RemainingService;
import org.millioncall.yueyoga.admin.service.SystemService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

//--created by lisj on 2014.03.06
@Controller
public class ProuductRemainingAction extends BaseAction {
	private ProductRemainingService productRemainingService;
	private RemainingService remainingService;
	private MemberService memberService;
	private SystemService systemService;
	private OrderService orderService;
	private OrderDetailService orderDetailService;
	private ProductService productService;
	private UserService userService;
	
	
	/**
	 * 产品延期
	 */
	@RequestMapping(value = "/updateProRemainingEndTime.jhtml")
	public void updateProRemainingEndTime(HttpServletRequest request,
			HttpServletResponse response, ModelMap model){
		String msg = "{\"success\":false}";
		
		Map<String, Object> map = new HashMap<String, Object>();
		String joinIds = request.getParameter("ids");
		String count = request.getParameter("count");
		
		Integer intCount = null;
		if(StringUtils.isNotBlank(count)){
			intCount = Integer.valueOf(count);
		}
		
		if(StringUtils.isNotBlank(joinIds) && intCount != null){
			map.put("counts", intCount);
			String[] ids = joinIds.split(",");
			if(ids != null && ids.length>0){
				for(String id : ids){
					ProductRemaining pr = this.productRemainingService.findProductRemainingById(Integer.valueOf(id));
					Date end = pr.getEndTime();
					Calendar can = Calendar.getInstance();
					can.setTime(end);
					can.add(Calendar.DAY_OF_MONTH, intCount);
					pr.setEndTime(can.getTime());
					
					boolean b = this.productRemainingService.updateProductRemaining(pr);
				}
			}
		}
		msg = "{\"success\":true}";
		WebAppUtils.ajaxResponse(response, msg);
	}
	
	/**
	 * 更改产品剩余次数
	 */
	@RequestMapping(value = "/updateProRemainingRestTimes.jhtml")
	public void updateProRemainingRestTimes(HttpServletRequest request,
			HttpServletResponse response, ModelMap model){
		String msg = "{\"success\":false}";
		
		Map<String, Object> map = new HashMap<String, Object>();
		String joinIds = request.getParameter("ids");
		String count = request.getParameter("count");
		Integer intCount = null;
		if(StringUtils.isNotBlank(count)){
			intCount = Integer.valueOf(count);
		}
		
		if(StringUtils.isNotBlank(joinIds) && intCount != null){
			map.put("counts", intCount);
			String[] ids = joinIds.split(",");
			if(ids != null && ids.length>0){
				for(String id : ids){
					map.put("id", Integer.valueOf(id));
					productRemainingService.updateProductRemaining(map);
				}
			}
		}
		msg = "{\"success\":true}";
		WebAppUtils.ajaxResponse(response, msg);
	}
	

	@RequestMapping(value = "/updateProRemainingTime.jhtml")
	public void updateProRemainingTime(String proRemainIds,
			String proBeginTime, String proEndTime, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);
		String msg = null;
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(proBeginTime)) {
			map.put("beginTime", proBeginTime);
		}
		if (StringUtils.isNotBlank(proEndTime)) {
			map.put("endTime", proEndTime);
		}
		String[] ids = proRemainIds.split(",");
		int count = 0;
		if (ids.length > 0) {
			for (String id : ids) {
				map.put("id", id);
				if (productRemainingService.updateProductRemaining(map)) {
					count += 1;
				}
			}
		}
		msg = count > 0 ? "gts" : "gtf";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 产品续费 注： 产品续费，即为对产品再进行一次购买操作， · 重新生成一个购买订单，重新生成一个产品使用情况记录
	 * 
	 * @param proRemainIds
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/renewalsProducts.jhtml")
	public void renewalsProducts(String productIds, String memberId,
			String sellerId, String proBeginTime, String proEndTime,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		super.initFrontHeader(request, model);
		String msg = null;
		msg = "{'success':false, 'msg':'产品续费失败!'}";
		Date beginTime = null;
		Date endTime = null;
		if (StringUtils.isBlank(proBeginTime)) {
			msg = "{'success':false, 'msg':'请选择开始时间!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		beginTime = DateTimeUtils.getInstance().parse(proBeginTime,
				"yyyy-MM-dd HH:mm:ss");
		if (StringUtils.isBlank(proEndTime)) {
			msg = "{'success':false, 'msg':'请选择结束时间!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (StringUtils.isBlank(sellerId)) {
			msg = "{'success':false, 'msg':'请选择负责人!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		endTime = DateTimeUtils.getInstance().parse(proEndTime,
				"yyyy-MM-dd HH:mm:ss");

		if (StringUtils.isNotBlank(productIds)
				&& StringUtils.isNotBlank(memberId)) {
			String[] proIds = productIds.split(",");
			// --账户金额
			Double zhje = 0.0d;
			// --账户余额
			Double zhye = 0.0d;
			// --续费产品的总金额
			Double xfzje = 0.0d;
			Member member = new Member();
			List<Product> products = new ArrayList<Product>();
			Order order = new Order();
			order.setState(1);
			order.setDiscount(0.0);
			// --1.创建续费订单
			// --2.创建续费订单详情
			// --3.
			if (proIds != null && proIds.length > 0) {
				if (StringUtils.isNotBlank(memberId)) {
					Map<String, Object> map1 = new HashMap<String, Object>();
					List<Integer> groupIds1 = new ArrayList<Integer>();
					for (Group group : this.getUser(request).getGroups()) {
						groupIds1.add(group.getId());
					}
					map1.put("groups", groupIds1);
					map1.put("id", Integer.parseInt(memberId));
					map1.put("hallcode", this.getUser(request).getOrganizationId());
					member = this.memberService.findById(map1);
					order.setMember(member);
				}
				Remaining remaining = remainingService.findyje(Integer
						.valueOf(memberId));
				if (remaining != null) {
					zhje = remaining.getRemaining();
					zhye = zhje;
				}

				for (String proId : proIds) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("productId", proId);
					List<Integer> groupIds = new ArrayList<Integer>();
					for (Group group : this.getUser(request).getGroups()) {
						groupIds.add(group.getId());
					}
					params.put("groups", groupIds);
					params.put("hallcode", this.getUser(request).getOrganizationId());
					Product p = productService.findById(params);
					if (p != null) {
						// --续费产品总价格
						xfzje = NumberUtils.add(xfzje, p.getPrice());
						products.add(p);
					}
				}
				// --账户余额是否充足
				if (zhye < xfzje) {
					msg = "{'success':true, 'msg':'账户余额不足，请及时充值!'}";
					WebAppUtils.ajaxResponse(response, msg);
					return;
				} else {
					int counts = 0;
					if (products != null && !products.isEmpty()) {
						// --1.创建续费订单
						order.setType("续费");
						order.setMoney(xfzje);
						order.setActualMoney(xfzje);
						order.setInputTime(new Date());
						order.setMember(member);
						User seller = userService.findById(sellerId);
						order.setSellerId(sellerId);
						order.setSeller(seller);
						order.setPayType(1);
						// 计算获得积分
						Site site = systemService.getSystem();
						int score = (int) (xfzje / site.getToScore());
						order.setScore(score);
						score += remaining.getScore();
						remaining.setScore(score);
						if (orderService.save(order) > 0) {
							for (Product pro : products) {
								ProductRemaining pr = new ProductRemaining();
								pr.setProductId(pro.getProductId());
								pr.setMemberId(member.getMemberid());
								pr.setCounts(pro.getCounts());
								pr.setBeginTime(beginTime);
								pr.setEndTime(endTime);
								if (productRemainingService
										.saveProductRemaining(pr)) {
									OrderDetail od = new OrderDetail();
									od.setOrder(order);
									od.setProduct(pro);
									od.setProRemainId(pr.getId());
									if (orderDetailService.save(od) > 0) {
										counts += 1;
									}
								}
							}
						}
					}
					// --处理账户余额
					if (counts > 0) {
						zhye = NumberUtils.sub(zhje, xfzje);
						if (zhye != zhje) {
							remaining.setRemaining(zhye);

							// --是否修改账户余额成功
							if (remainingService.updateRemainingById(remaining)) {
								msg = "{'success':true, 'msg':'产品续费成功!'}";
							}
						} else {
							msg = "{'success':true, 'msg':'产品续费失败!'}";
						}
					}
				}
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 产品退款 注：产品退款即产生一个退费订单(购买订单)， 删除会员所退款的产品关联信息(会员产品关联，产品的使用情况)。
	 * 
	 * @param proRemainIds
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/refundProducts.jhtml")
	public void refundProducts(String proRemainIds, String memberId,
			String sellerId, String refundMoney, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);
		String msg = null;
		msg = "{'success':false, 'msg':'产品退款失败!'}";
		Double rfMoney = 0.0d;
		if (StringUtils.isNotBlank(refundMoney)) {
			rfMoney = Double.valueOf(refundMoney);
		}
		// --账户金额
		Double zhje = 0.0d;
		Order order = new Order();
		order.setDiscount(0.0);
		order.setState(1);
		Member member = new Member();
		Remaining remaining = new Remaining();
		if (StringUtils.isNotBlank(memberId)) {
			Map<String, Object> map1 = new HashMap<String, Object>();
			List<Integer> groupIds1 = new ArrayList<Integer>();
			for (Group group : this.getUser(request).getGroups()) {
				groupIds1.add(group.getId());
			}
			map1.put("groups", groupIds1);
			map1.put("id", Integer.parseInt(memberId));
			map1.put("hallcode", this.getUser(request).getOrganizationId());
			member = this.memberService.findById(map1);
			remaining = remainingService.findyje(Integer.valueOf(memberId));
			order.setMember(member);
		}
		if (remaining != null) {
			zhje = remaining.getRemaining();
		}
		int counts = 0;
		// --2.创建退款订单详情
		if (StringUtils.isNotBlank(proRemainIds)) {
			String[] prIds = proRemainIds.split(",");
			// --1.创建退款订单
			order.setType("退款");
			order.setMember(member);
			order.setSellerId(sellerId);
			order.setSeller(userService.findById(sellerId));
			order.setMoney(rfMoney);
			order.setInputTime(new Date());
			order.setActualMoney(rfMoney);
			//设置默认支付方式
			order.setPayType(1);
			// --通过产品使用记录编号获取产品
			if (prIds != null && prIds.length > 0) {
				orderService.save(order);
				for (String proId : prIds) {
					ProductRemaining pr = productRemainingService
							.findProductRemainingById(Integer.parseInt(proId));
					// --根据会员产品的使用情况获取要退费的产品
					if (pr != null && pr.getProduct() != null) {
						Product product = pr.getProduct();
						OrderDetail od = new OrderDetail();
						od.setProduct(product);
						od.setOrder(order);
						counts += orderDetailService.save(od);
					}
				}
			}
			// --处理账户余额
			if (counts > 0) {
				// --获得退款金额，rfMoney,用户手动输入退款金额
				zhje = NumberUtils.add(zhje, rfMoney);
				remaining.setRemaining(zhje);
				// --是否修改账户余额成功
				if (remainingService.updateRemainingById(remaining)) {
					if (productRemainingService
							.refundProductsByIds(proRemainIds)) {
						msg = "{'success':true, 'msg':'产品退款成功!'}";
					}
				}
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	public ProductRemainingService getProductRemainingService() {
		return productRemainingService;
	}

	public void setProductRemainingService(
			ProductRemainingService productRemainingService) {
		this.productRemainingService = productRemainingService;
	}

	public RemainingService getRemainingService() {
		return remainingService;
	}

	public void setRemainingService(RemainingService remainingService) {
		this.remainingService = remainingService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public SystemService getSystemService() {
		return systemService;
	}

	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public OrderDetailService getOrderDetailService() {
		return orderDetailService;
	}

	public void setOrderDetailService(OrderDetailService orderDetailService) {
		this.orderDetailService = orderDetailService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
